package com.lock.controller;

import com.lock.content.Result;
import com.lock.request.BalanceRequest;
import com.lock.request.StockRequest;
import com.lock.service.OptimisticLockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/optimistic")
public class OptimisticLockController {
    @Autowired
    private OptimisticLockService optimisticLockService;

    /**
     * 基于乐观锁的库存扣减接口
     * 通过版本号机制实现乐观锁，适用于高并发、读多写少的库存管理场景
     * 支持自动重试版本冲突，避免因并发导致的库存超卖问题
     */
    @PostMapping("/decreaseStock")
    public Result<?> decreaseStockByVersion(@RequestBody StockRequest request) {
        boolean success = optimisticLockService.decreaseStockByVersion(
                request.getProductId(), request.getQuantity());
        return success ? Result.success() : Result.fail("库存不足或更新失败");
    }

    /**
     * 基于乐观锁的余额扣减接口
     * 通过SQL条件实现乐观锁，适用于用户账户余额、积分等资金类数据的并发扣减
     * 直接通过SQL条件校验余额充足性，避免超扣问题
     */
    @PostMapping("/decreaseBalance")
    public Result<?> decreaseBalance(@RequestBody BalanceRequest request) {
        boolean success = optimisticLockService.decreaseBalance(
                request.getUserId(), request.getAmount());
        return success ? Result.success() : Result.fail("余额不足");
    }
}
